package service

import (
	"context"

	"gitee.com/hust-ideas/little-genius-backend/model"
	"gitee.com/hust-ideas/little-genius-backend/util/pwd"
)

func (s *ServiceContext) AuthLoginPost(req model.AuthLoginReq, c context.Context) (resp *model.AuthLoginResp, err error) {
	// 检查用户 email 是否存在
	if _, err = s.Model.UserModel.FindOneByEmail(req.Email); err != nil {
		return nil, model.ErrDismatchPasswordorUser
	}
	// 检查密码是否正确
	u, err := s.Model.UserModel.FindOneByEmail(req.Email)
	if err != nil {
		return nil, model.ErrDismatchPasswordorUser
	}
	if !pwd.CheckPasswordHash(req.Password, u.UPassword) {
		return nil, model.ErrDismatchPasswordorUser
	}
	// 生成 token
	token, err := pwd.GenToken(u.UEmail)
	if err != nil {
		return nil, err
	}
	resp = &model.AuthLoginResp{
		Token: token,
	}
	return
}
